<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <link type="text/css" rel="stylesheet" href="/stylesheets/main.css"/>
    <link type="text/css" rel="stylesheet" href="/stylesheets/datePicker.css"/>
    <script src="scripts/jquery-1.10.2.min.js"></script>
	<script src="scripts/date.js"></script>
    <script src="scripts/jquery.datePicker.js" ></script>
    <script src="scripts/jquery.blockUI.js" ></script>
    <script>
    var currentDate = getNormalizedDate();
    var comicsDates = {"duplex":getNormalizedDate(), "poochcafe":getNormalizedDate(), "pearlsbeforeswine":getNormalizedDate()};
    // TODO: implement last viewed date loading from cookies
    
    var comicsNames = ["duplex", "poochcafe", "pearlsbeforeswine"];
    
    // Dynamically resolve
    var imageWidth = 800;
    
    // Images storage
    var loadedImages = {};
    
    // Update current date
    function moveCurrentDate(increment, comicsName) {
    	currentDate = getPushedDate(increment, comicsName);
    }
    
    // Calculate next image date
    function getPushedDate(increment, comicsName) {
    	var newDate = new Date(comicsDates[comicsName]);
    	newDate.setDate(newDate.getDate()+increment);
    	return newDate;
    }
    
    function formatDate(d) {
    	return d.getFullYear()+"/"+getNumber2((d.getMonth()+1))+"/"+getNumber2(d.getDate());
    }
    
    // Format number as 2 decimal places
    function getNumber2(number) {
    	return number < 10 ? "0"+number:number;
    }
    
    function displayImage(comics, d) {
		$("#comicsImage_"+comics).attr({src:loadedImages["'"+comics+"'"]["'"+formatDate(d)+"'"].src});
		$("#imageTitle_"+comics).text(comics + " - " + formatDate(d));
		comicsDates[comics] = d;
		setComicsDateCookie(comics, d);
    }
    
    function storeLoadedImage(imageUrl, comics, date) {
    		var img = new Image();
    		if (typeof loadedImages["'"+comics+"'"] === "undefined") {
    			loadedImages["'"+comics+"'"] = {};
    		} 
    		loadedImages["'"+comics+"'"]["'"+formatDate(date)+"'"] = img;
    		img.src = imageUrl;
   			displayImage(comics, date);
// This is potential overhead - if image URL is received from the server it should be available to display.
// No significant reason to wait until it's cached
//    		img.onload = function () {
//    		};
    }
    
    /*
    	Loads image for the current date if not cached.
    	Loads image from cache if already loaded.
    */
    function loadAndDisplayImage(comics, date) {
   		if (!(typeof loadedImages["'"+comics+"'"] === "undefined")) {
   			if (!(typeof loadedImages["'"+comics+"'"]["'"+formatDate(date)+"'"] === "undefined")) {
   				displayImage(comics, date);
   				return;
   			}
   		}
        $('#image_container_'+comics).block({ message: "<div style='text-align:center'>Loading<br/>image</div>"}); 
    	$.get("/gcload", {comics:comics, date:formatDate(date), size:imageWidth}, function(imageUrl) {
    		storeLoadedImage(imageUrl, comics, date);
            $('#image_container_'+comics).unblock(); 
    	})
    	.fail(function(){
            $('#image_container_'+comics).unblock(); 
        	alert('Data not loaded');
    	});
    }
    
    // Processing user action - date change
    function handleImageSwipe(increment, comicsName) {
    	var d = getPushedDate(increment, comicsName);
    	loadAndDisplayImage(comicsName, d);
    }

    function getNormalizedDate() {
    	var result = new Date();
        result.setHours(0);
        result.setMinutes(0);
        result.setSeconds(0);
        result.setMilliseconds(0);
    	return result;
    }

    // Move date forward - next day
    // Exception - no data in the future
    function handleImageSwipeNext(swipeEvent) {
    	var comicsName = getComicsNameFromId(swipeEvent.target.id);
    	var newDate = getPushedDate(1, comicsName);
    	var curDate = getNormalizedDate();
    	if (newDate > curDate) {
    		alert('No data after today!');
    		return;
    	}
    	handleImageSwipe(1, comicsName);
    }
    
    // Move date backward - prev day
    function handleImageSwipePrev(swipeEvent) {
    	handleImageSwipe(-1, getComicsNameFromId(swipeEvent.target.id));
    }

    function getComicsNameFromId(idstr) {
    	return idstr.substr(idstr.lastIndexOf("_")+1);
    }
    
    var cookieExp = 365*24*60*60*1000;// 1 yr worth of ms from now
    function setComicsDateCookie(comicsName, d) {
    	document.cookie = comicsName + "=" + d.getTime() + "; expires="+(new Date(d.getTime()+cookieExp)).toUTCString();
    }
    
    function getComicsDatesFromCookie() {
    	var comicsDatesCookies = document.cookie.split(";");
    	for (idx in comicsDatesCookies) {
    		var cookieData = comicsDatesCookies[idx].trim().split("=");
    		if (comicsNames.indexOf(cookieData[0])>=0) {
    			comicsDates[cookieData[0]] = new Date(1*cookieData[1]);
    		};
    	};
    }
    
    function attachNavigation(comicsName) {
    	$("#next_"+comicsName).on("click", handleImageSwipeNext);
    	$("#prev_"+comicsName).on("click", handleImageSwipePrev);
    	
    	$("#imageTitle_"+comicsName).datePicker({createButton:false, startDate: '01/01/1990', endDate: (new Date()).asString()})
    		.bind('click', function() {
    				$(this).dpDisplay();
    				this.blur();
    				return false;
    		})
    		.bind('dateSelected', function(e, selectedDate, $td) {
    	    	loadAndDisplayImage(comicsName, selectedDate);
    		});
    }
    
    $(document).ready(function(){
    	getComicsDatesFromCookie();
    	for (cn in comicsNames) {
			loadAndDisplayImage(comicsNames[cn], comicsDates[comicsNames[cn]]);
			attachNavigation(comicsNames[cn]);
    	}
    });
    
/*     
 	$(document).ajaxError(function(event, request, settings, error){
    	// Handle errors here: request.status
        $('#image_container').unblock(); 
    	alert('Data not loaded');
    });
 */
 </script>
</head>

<body>
<div id="main_container_duplex" style="position:relative;float:left;width:800px">
	<div id="image_container_duplex" style="width:100%;">
		<div id="prev_duplex" style="float:left">Prev</div><div id="imageTitle_duplex" style="float:left;margin-left:1em;margin-right:1em;">...</div><div id="next_duplex" style="float:left;">Next</div>
		<div style="clear:both"></div>
		<img id="comicsImage_duplex"/>
	</div>
</div>
<div style="clear:both;"></div>
<div style="margin-top:2em;margin-bottom:2em;"></div>
<div id="main_container_poochcafe" style="position:relative;float:left;width:800px">
	<div id="image_container_poochcafe" style="width:100%;">
		<div id="prev_poochcafe" style="float:left">Prev</div><div id="imageTitle_poochcafe" style="float:left;margin-left:1em;margin-right:1em;">...</div><div id="next_poochcafe" style="float:left;">Next</div>
		<div style="clear:both"></div>
		<img id="comicsImage_poochcafe"/>
	</div>
</div>
<div style="clear:both;"></div>
<div style="margin-top:2em;margin-bottom:2em;"></div>
<div id="main_container_pearlsbeforeswine" style="position:relative;float:left;width:800px">
	<div id="image_container_pearlsbeforeswine" style="width:100%;">
		<div id="prev_pearlsbeforeswine" style="float:left">Prev</div><div id="imageTitle_pearlsbeforeswine" style="float:left;margin-left:1em;margin-right:1em;">...</div><div id="next_pearlsbeforeswine" style="float:left;">Next</div>
		<div style="clear:both"></div>
		<img id="comicsImage_pearlsbeforeswine"/>
	</div>
</div>
</body>
</html>
